package com.milling.business.service.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.milling.common.core.redis.RedisCache;
import com.milling.common.utils.StringUtils;
import com.milling.common.utils.http.WmsApiUtils;
import com.milling.common.utils.sql.DbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.milling.business.mapper.WmsDrillinfoStockMapper;
import com.milling.business.domain.WmsDrillinfoStock;
import com.milling.business.service.IWmsDrillinfoStockService;

/**
 * 后库库存Service业务层处理
 *
 * @author X
 * @date 2025-04-09
 */
@Service
public class WmsDrillinfoStockServiceImpl implements IWmsDrillinfoStockService
{
    private static final Logger logger = LoggerFactory.getLogger(WmsDrillinfoStockServiceImpl.class);

    @Autowired
    private WmsDrillinfoStockMapper wmsDrillinfoStockMapper;

    @Autowired
    private DbUtils dbUtils;

    @Autowired
    private RedisCache redisCache;


    /**
     * 查询后库库存
     *
     * @param drillInfo 后库库存主键
     * @return 后库库存
     */
    @Override
    public WmsDrillinfoStock selectWmsDrillinfoStockByDrillInfo(String drillInfo)
    {
        return wmsDrillinfoStockMapper.selectWmsDrillinfoStockByDrillInfo(drillInfo);
    }

    /**
     * 查询后库库存列表
     *
     * @param wmsDrillinfoStock 后库库存
     * @return 后库库存
     */
    @Override
    public List<WmsDrillinfoStock> selectWmsDrillinfoStockList(WmsDrillinfoStock wmsDrillinfoStock)
    {
        return wmsDrillinfoStockMapper.selectWmsDrillinfoStockList(wmsDrillinfoStock);
    }

    /**
     * 新增后库库存
     *
     * @param wmsDrillinfoStock 后库库存
     * @return 结果
     */
    @Override
    public int insertWmsDrillinfoStock(WmsDrillinfoStock wmsDrillinfoStock)
    {
        return wmsDrillinfoStockMapper.insertWmsDrillinfoStock(wmsDrillinfoStock);
    }

    /**
     * 修改后库库存
     *
     * @param wmsDrillinfoStock 后库库存
     * @return 结果
     */
    @Override
    public int updateWmsDrillinfoStock(WmsDrillinfoStock wmsDrillinfoStock)
    {
        return wmsDrillinfoStockMapper.updateWmsDrillinfoStock(wmsDrillinfoStock);
    }

    /**
     * 批量删除后库库存
     *
     * @param drillInfos 需要删除的后库库存主键
     * @return 结果
     */
    @Override
    public int deleteWmsDrillinfoStockByDrillInfos(String[] drillInfos)
    {
        return wmsDrillinfoStockMapper.deleteWmsDrillinfoStockByDrillInfos(drillInfos);
    }

    /**
     * 删除后库库存信息
     *
     * @param drillInfo 后库库存主键
     * @return 结果
     */
    @Override
    public int deleteWmsDrillinfoStockByDrillInfo(String drillInfo)
    {
        return wmsDrillinfoStockMapper.deleteWmsDrillinfoStockByDrillInfo(drillInfo);
    }

    @Override
    public void syncStock() {
        WmsApiUtils wmsApiUtils = new WmsApiUtils();
        String result = wmsApiUtils.queryInventory();

        if(StringUtils.isNotEmpty(result)) {
            JSONObject jsonObject2 = JSONObject.parseObject(result);
            // 解析JSON字符串

            //先清理之前的缓存信息
//            Collection<String> collection = redisCache.keys("DRILLTYPE-");
//            redisCache.deleteObject(collection);

            Collection<String> keys = redisCache.keys("DRILLTYPE-*");
            if (keys != null && !keys.isEmpty()) {
                redisCache.deleteObject(keys);
                logger.info("已清理 " + keys.size() + " 条缓存");
            }

            // 用于检测缓存覆盖问题的Map
            Map<String, String> cacheMap = new HashMap<>();
            Map<String, String> conflictMap = new HashMap<>();

            // 提取DataList数组
            JSONArray dataList = jsonObject2.getJSONArray("DataList");
            if (dataList != null) {
                int z = dbUtils.executeUpdate("delete from wms_drillinfo_stock");
//                dbUtils.executeQuery("delete from wms_drillinfo_stock");
                String[] sqls = new String[dataList.size()];
                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject item = dataList.getJSONObject(i);
                    String drillInfo = item.getString("drill_info");
                    String drillCount = item.getString("drill_count");
                    String boxCount = item.getString("box_Count");
                    String drillSize = drillInfo.substring(0, 4);
                    String drillType = drillInfo.substring(4, 5);
                    String drillGrindCount = drillInfo.substring(7, 8);
                    String holeType = "";
                    if("7".equals(drillType) || "8".equals(drillType)){
                        holeType = "2";
                    } else {
                        holeType = "1";
                    }

                    // 构建缓存键
                    String grindCountKey = "DRILLTYPE-GRINDCOUNT-"+drillSize+"-" + holeType + "-" + drillGrindCount;
                    String sizeKey = "DRILLTYPE-"+drillSize + "-" + holeType;

                    // 检测并记录缓存冲突
                    if (cacheMap.containsKey(grindCountKey)) {
                        conflictMap.put(grindCountKey, "冲突：" + cacheMap.get(grindCountKey) + " vs " + drillInfo);
                        logger.warn("检测到缓存键冲突: {} - 原值: {}, 新值: {}", grindCountKey, cacheMap.get(grindCountKey), drillInfo);
                    }
                    if (cacheMap.containsKey(sizeKey)) {
                        conflictMap.put(sizeKey, "冲突：" + cacheMap.get(sizeKey) + " vs " + drillInfo);
                        logger.warn("检测到缓存键冲突: {} - 原值: {}, 新值: {}", sizeKey, cacheMap.get(sizeKey), drillInfo);
                    }

                    // 优先级策略：研磨次数越小优先级越高（新针优先）
                    boolean shouldUpdateGrindCount = true;
                    boolean shouldUpdateSize = true;

                    if (cacheMap.containsKey(grindCountKey)) {
                        String existingDrillInfo = cacheMap.get(grindCountKey);
                        int existingGrindCount = Integer.parseInt(existingDrillInfo.substring(7, 8));
                        int currentGrindCount = Integer.parseInt(drillGrindCount);

                        // 如果现有的研磨次数更小（更新），则不更新
                        if (existingGrindCount < currentGrindCount) {
                            shouldUpdateGrindCount = false;
                            logger.info("保持现有研磨次数缓存：{} (研磨次数 {} < {})", existingDrillInfo, existingGrindCount, currentGrindCount);
                        }
                    }

                    if (cacheMap.containsKey(sizeKey)) {
                        String existingDrillInfo = cacheMap.get(sizeKey);
                        int existingGrindCount = Integer.parseInt(existingDrillInfo.substring(7, 8));
                        int currentGrindCount = Integer.parseInt(drillGrindCount);

                        // 对于尺寸键，也优先保留研磨次数更小的
                        if (existingGrindCount < currentGrindCount) {
                            shouldUpdateSize = false;
                            logger.info("保持现有尺寸缓存：{} (研磨次数 {} < {})", existingDrillInfo, existingGrindCount, currentGrindCount);
                        }
                    }

                    if (shouldUpdateGrindCount) {
                        cacheMap.put(grindCountKey, drillInfo);
                        redisCache.setCacheObject(grindCountKey, drillInfo);
                        logger.debug("缓存更新(研磨次数)：{} -> {}", grindCountKey, drillInfo);
                    }

                    if (shouldUpdateSize) {
                        cacheMap.put(sizeKey, drillInfo);
                        redisCache.setCacheObject(sizeKey, drillInfo);
                        logger.debug("缓存更新(尺寸)：{} -> {}", sizeKey, drillInfo);
                    }
//                    redisCache.setCacheObject("DRILLTYPE-"+drillSize+"-"+ drillCategory + "-" + drillGrindCount, drillInfo);
//                    String sql = "insert into wms_drillinfo_stock(drill_info,drill_count,box_count,drill_size,drill_type,drill_grind_count) values('" + drillInfo + "'," + drillCount + "," + boxCount + ",'" + drillSize + "','" + drillType + "'," + drillGrindCount + ")";
                    String sql = "insert into wms_drillinfo_stock(drill_info,drill_count,box_count,drill_size,drill_category,drill_type,drill_grind_count, create_time) values('" + drillInfo.trim() + "'," + drillCount + "," + boxCount + ",'" + drillSize + "','" + holeType + "','" + drillType + "'," + drillGrindCount + ", now())";
//                    logger.info("sql:{}", sql);
                    sqls[i] = sql;
                }
                dbUtils.batchUpdate(sqls);

                // 报告缓存冲突情况
                if (!conflictMap.isEmpty()) {
                    logger.warn("同步完成，检测到 {} 个缓存冲突：", conflictMap.size());
                    for (Map.Entry<String, String> entry : conflictMap.entrySet()) {
                        logger.warn("冲突键: {} - {}", entry.getKey(), entry.getValue());
                    }
                } else {
                    logger.info("同步完成，无缓存冲突");
                }
            }
        }
    }
}
